#include "stdafx.h"
#include "WMPPlusHookData.h"
#include "..\WMP\Common.h"

#pragma unmanaged

void Encode(LPTSTR str) {
	for(; *str; str++) {
		if (*str == '%' && str[1]) {
			TCHAR buf[3] = {str[1], str[2], 0};
			LPTSTR stop;
			long chr = _tcstol(buf, &stop, 16);
			if (stop && *stop)
				continue;
			*str = (TCHAR)chr;
			size_t len = _tcslen(str+3);
			_tcsncpy(str+1, str+3, len);
			str[len+1] = 0;
		} else if (*str == '+') {
			*str = ' ';
		}
	}
}

BOOL WINAPI ResolveLabel(LPTSTR label, int clabel, LPCTSTR lib, LPTSTR reslib, int creslib) {
	*reslib = 0;
	if (_tcsncmp(label, _T("res://"), 6) != 0)
		return true;
	TCHAR* file = label+6;
	TCHAR* sep1 = _tcschr(file, '/');
	if (!sep1)
		return false;
	TCHAR* name = _tcschr(sep1+1, '/');
	if (name) {
		if (_tcschr(name+1, '/'))
			return false;
	} else {
		name = sep1;
	}
	*sep1 = 0; name++;
	Encode(file);
	Encode(name);
	while(*file == ' ') file++;
	while(*name == ' ') name++;
	if (!*file || *name != '#')
		return false;
	LPTSTR stop;
	int res = _tcstol(name+1, &stop, 10);
	if (stop && *stop)
		return false;
	HMODULE module = NULL;
	try {
		module = LoadLibraryEx(file, NULL,
			LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);
		if (!module && lib && *lib)
			module = LoadLibraryEx(lib, NULL,
				LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);
		if (module) {
			_tcscpy(reslib, file);
			if (!LoadString(module, res, label, clabel))
				*reslib = 0;
		}
		if (module)
			FreeLibrary(module);
	} catch(...) {
		if (module)
			FreeLibrary(module);
		*reslib = 0;
	}
	return !!*reslib;
}

WMPPlusHookData::WMPPlusHookData() {
	MajorVersion = 0;
	MinorVersion = 0;
	Libraries = (IMPORT_LIBRARY)0;
}
